// 手动实现一个简易版 promise
class myPromise {
  constructor(fn) {
    this.state = "PADDING";
    this.resolvedCallbacks = [];
    this.rejectedCallbacks = [];
    this.value = null;
    fn(this.resolve.bind(this), this.reject.bind(this))
  }

  resolve(value) {
    if (this.state === "PADDING") {
      this.state = "RESOLVED";
      this.value = value;
      this.resolvedCallbacks.forEach(cb => cb(this.value));
    }
  }

  reject(value) {
    if (this.state === "PADDING") {
      this.state = "REJECTED"
      this.value = value;
      this.rejectedCallbacks.forEach(cb => cb(this.value));
    }
  }

  then(resolve = function () {}, reject = function () {}) {
    if (this.state === "PADDING") {
      this.resolvedCallbacks.push(resolve);
      this.rejectedCallbacks.push(reject);
    }
    if (this.state === "RESOLVED") {
      resolve(this.value);
    }
    if (this.state === "REJECTED") {
      reject(this.value);
    }
  }
}


let p = new myPromise((reject, resolve) => {
  let a = 1;
  if (a) {
    reject(a);
  } else {
    resolve('发生了错误')
  }
})

p.then((re) => {
  console.log(re);
},(error) => {
  console.log(error);
})